package org.hbhk.hxl.gateway.filter;

import org.hbhk.hxl.gateway.exception.RouteException;
import org.hbhk.hxl.gateway.model.Isolation;
import org.hbhk.hxl.gateway.services.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 
 * 服务的隔离处理
 *
 */
@Component
public class IsolationFilter implements GlobalFilter, Ordered {

	private final Logger logger = LoggerFactory.getLogger(IsolationFilter.class);

	@Override
	public int getOrder() {
		return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 8;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		String url = request.getURI().getPath();

		Isolation isolation = ServiceUtil.getIsolation(url);
		if (isolation == null) {
			return chain.filter(exchange);
		}

		if (isolation != null && isolation.getCounter() > 0) {
			boolean result = IsolationCounterUtil.validate(url, isolation.getCounter());
			if (!result) {
				logger.error("服务:" + url + "触发隔离保护单位时间:" + isolation.getTime() + "上限:" + isolation.getCounter());
				throw new RouteException("隔离保护:" + url);
			}
		}

		return chain.filter(exchange).then(Mono.fromRunnable(() -> {
			if (isolation != null && isolation.getCounter() > 0) {
				IsolationCounterUtil.decrement(url);
			}
		}));

	}

}